const fs = require('fs')
const fse = require('fs-extra')
const os = require('os')
const path = require('path')
const { chalk, toShortPluginId } = require('@vue/cli-shared-utils')


const isManualMode = answers => answers.preset === '__manual__' // 选择【Manually select features】时为 true

const defaultPreset = {
  useConfigFiles: false,
  cssPreprocessor: undefined,
  plugins: {
    '@vue/cli-plugin-babel': {},
    '@vue/cli-plugin-eslint': {
      config: 'base',
      lintOn: ['save']
    }
  }
}

const defaults = {
  lastChecked: undefined,
  latestVersion: undefined,

  packageManager: undefined,
  useTaobaoRegistry: undefined,
  presets: {
    'Default (Vue 3)': Object.assign({ vueVersion: '3' }, defaultPreset),
    'Default (Vue 2)': Object.assign({ vueVersion: '2' }, defaultPreset)
  }
}

function resolveIntroPrompts () {
  const presets = getPresets()
  // 名字优化
  const presetChoices = Object.entries(presets).map(([name, preset]) => {
    let displayName = name
    if (name === 'Default (Vue 2)' || name === 'Default (Vue 3)') {
      displayName = 'Default'
    }

    return {
      name: `${displayName} (${formatFeatures(preset)})`,
      value: name
    }
  })

  // 弄2个Prompt
  const presetPrompt = {
    name: 'preset',
    type: 'list',
    message: `Please pick a preset:`,
    choices: [
      ...presetChoices,
      {
        name: 'Manually select features',
        value: '__manual__'
      }
    ]
  }
  const featurePrompt = {
    name: 'features',
    when: isManualMode,
    type: 'checkbox',
    message: 'Check the features needed for your project:',
    choices: [],
    pageSize: 10
  }
  return {
    presetPrompt,
    featurePrompt
  }
}
function loadOptions() {
  const rcPath = path.join(os.homedir(), '.vuerc') // /Users/w/.vuerc

  if (fs.existsSync(rcPath)) {
    cachedOptions = JSON.parse(fs.readFileSync(rcPath, 'utf-8'));
    return cachedOptions
  }
}

function getPresets () {
  const savedOptions = loadOptions()
  return Object.assign({}, savedOptions.presets, defaults.presets)
}

const formatFeatures = (preset) => {
  const versionInfo = chalk.yellow(`[Vue ${preset.vueVersion || 2}] `)
  const features = getFeatures(preset)

  return versionInfo + features.map(dep => {
    dep = toShortPluginId(dep)
    return chalk.yellow(dep)
  }).join(', ')
}



const getFeatures = (preset) => {
  const features = []
  if (preset.router) {
    features.push('router')
  }
  if (preset.vuex) {
    features.push('vuex')
  }
  if (preset.cssPreprocessor) {
    features.push(preset.cssPreprocessor)
  }
  const plugins = Object.keys(preset.plugins).filter(dep => {
    return dep !== '@vue/cli-service'
  })
  features.push.apply(features, plugins)
  return features
}

function getPromptModules() {
  return [
    'vueVersion',
    'babel',
    'typescript',
    'pwa',
    'router',
    'vuex',
    'cssPreprocessors',
    'linter',
    'unit',
    'e2e'
  ].map(file => require(`../promptModules/${file}`))
}

async function writeFileTree (dir, files, previousFiles, include) {
  Object.keys(files).forEach((name) => {
    const filePath = path.join(dir, name)
    fse.ensureDirSync(path.dirname(filePath))
    fse.writeFileSync(filePath, files[name])
  })
}

module.exports = {
  getPresets,
  resolveIntroPrompts,
  formatFeatures,
  loadOptions,
  isManualMode,
  getPromptModules,
  writeFileTree
}